/**
 * 
 */
package service;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * https://blog.csdn.net/a_runner/article/details/80640675
 * 两条线程循环打印1-100
 * 
 * @author jiangnk001
 *
 */
public class MultiThreadPrintNumber3 {

	private static Lock lock = new ReentrantLock();
	
	private static Condition condition = lock.newCondition();
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		new Thread(()->{
			for(int i = 1;i < 100;i+=2){
				lock.lock();
				condition.signal();
				System.out.println(Thread.currentThread().getName()+ " " + i);
				try {
					// wait 必须在 synchronized 块中使用
					condition.await();
				} catch (Exception e) {
					e.printStackTrace();
				}finally {
					lock.unlock();
				}
				
			}
		}).start();
		new Thread(()->{
			for(int i = 2;i <= 100;i+=2){
				lock.lock();
				condition.signal();
				System.out.println(Thread.currentThread().getName()+ " " + i);
				try {
					// wait 必须在 synchronized 块中使用
					condition.await();
				} catch (Exception e) {
					e.printStackTrace();
				}finally {
					lock.unlock();
				}
			}
		}).start();
	}
}


